<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>MCP代码生成系统 v2.0 - 管理控制台</title>
    <!-- 使用中国镜像CDN -->
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/tailwindcss/2.2.19/tailwind.min.css">
    <script src="https://cdn.bootcdn.net/ajax/libs/alpinejs/3.13.3/cdn.min.js" defer></script>
    <link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.2/css/all.min.css" rel="stylesheet">
    <style>
        .gradient-bg {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
        .card-hover {
            transition: all 0.3s ease;
        }
        .card-hover:hover {
            transform: translateY(-4px);
            box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
        }
        .status-indicator {
            width: 12px;
            height: 12px;
            border-radius: 50%;
            display: inline-block;
            margin-right: 8px;
        }
        .status-online { background-color: #10b981; }
        .status-offline { background-color: #ef4444; }
        .status-loading { background-color: #f59e0b; animation: pulse 2s infinite; }
        
        /* 拖拽动画 */
        .drag-over {
            animation: dragPulse 1s infinite;
        }
        
        @keyframes dragPulse {
            0%, 100% { transform: scale(1); }
            50% { transform: scale(1.02); }
        }
        
        /* 上传进度条动画 */
        .progress-bar {
            transition: width 0.3s ease-in-out;
        }
        
        /* 成功状态动画 */
        .success-bounce {
            animation: successBounce 0.6s ease-out;
        }
        
        @keyframes successBounce {
            0% { transform: scale(1); }
            50% { transform: scale(1.05); }
            100% { transform: scale(1); }
        }
        
        /* 文件信息显示 */
        .file-info {
            background: linear-gradient(90deg, #f3f4f6, #e5e7eb);
            border-radius: 6px;
            padding: 8px 12px;
            margin-top: 8px;
        }
    </style>

</head>
<body class="bg-gray-50 font-sans" x-data="mcpDashboard()">
    <!-- 顶部导航 -->
    <nav class="gradient-bg shadow-lg">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between h-16">
                <div class="flex items-center">
                    <div class="flex-shrink-0">
                        <h1 class="text-2xl font-bold text-white">
                            <i class="fas fa-code mr-2"></i>
                            MCP代码生成系统 v2.0
                        </h1>
                    </div>
                </div>
                <div class="flex items-center space-x-4">
                    <button @click="refreshAllStatus()" 
                            class="bg-white bg-opacity-20 hover:bg-opacity-30 text-white px-4 py-2 rounded-lg transition-all duration-200">
                        <i class="fas fa-sync-alt mr-2" :class="{'fa-spin': isRefreshing}"></i>
                        刷新状态
                    </button>
                </div>
            </div>
        </div>
    </nav>

    <!-- 主要内容区域 -->
    <div class="max-w-7xl mx-auto py-6 px-4 sm:px-6 lg:px-8">
        
        <!-- 主要功能区域 -->
        <div class="mb-8">
            <!-- Excel 上传与代码生成 - 主要功能 -->
            <div class="bg-gradient-to-r from-blue-50 to-indigo-50 rounded-xl shadow-lg p-8 mb-8 border border-blue-200">
                <div class="flex items-center mb-6">
                    <div class="bg-blue-600 rounded-full p-3 mr-4">
                        <i class="fas fa-file-excel text-white text-2xl"></i>
                    </div>
                    <div>
                        <h2 class="text-3xl font-bold text-gray-900">Excel 文件上传与函数生成</h2>
                        <p class="text-lg text-gray-600 mt-1">上传Excel文件，自动生成MCP函数代码</p>
                    </div>
                </div>
                
                <!-- 上传区域 -->
                <div class="bg-white rounded-lg p-6 shadow-inner">
                    <div class="border-2 border-dashed border-gray-300 rounded-lg p-8 text-center transition-all duration-300" 
                         :class="{
                             'border-blue-400 bg-blue-50': selectedFile,
                             'border-green-400 bg-green-50': isDragOver,
                             'border-red-400 bg-red-50': dragError
                         }"
                         @dragover.prevent="handleDragOver"
                         @dragleave.prevent="handleDragLeave"
                         @drop.prevent="handleDrop">
                        <input type="file" id="excelFile" accept=".xlsx,.xls" class="hidden" @change="handleFileSelect">
                        <label for="excelFile" class="cursor-pointer block">
                            <i class="fas fa-cloud-upload-alt text-6xl mb-4 transition-colors duration-200" 
                               :class="{
                                   'text-blue-500': selectedFile,
                                   'text-green-500': isDragOver,
                                   'text-red-500': dragError,
                                   'text-gray-400': !selectedFile && !isDragOver && !dragError
                               }"></i>
                            <p class="text-xl text-gray-600 mb-3" x-show="!selectedFile && !isDragOver">
                                点击选择 Excel 文件或拖拽到此处
                            </p>
                            <p class="text-xl text-green-700 font-medium mb-3" x-show="isDragOver">
                                松开鼠标完成上传
                            </p>
                            <p class="text-xl text-blue-700 font-medium mb-3" x-show="selectedFile && !isDragOver" x-text="selectedFile ? selectedFile.name : ''"></p>
                            <p class="text-xl text-red-600 font-medium mb-3" x-show="dragError" x-text="dragErrorMessage"></p>
                            <p class="text-base text-gray-500">
                                支持 .xlsx 和 .xls 格式，最大 10MB
                            </p>
                            <div x-show="selectedFile" class="mt-3 text-sm text-gray-400">
                                文件大小: <span x-text="formatFileSize(selectedFile?.size)"></span>
                            </div>
                        </label>
                    </div>
                    
                    <!-- 上传进度条 -->
                    <div x-show="isUploading" class="mt-6">
                        <div class="bg-gray-200 rounded-full h-4 mb-3 overflow-hidden">
                            <div class="bg-gradient-to-r from-blue-500 to-blue-600 h-4 rounded-full progress-bar" 
                                 :style="`width: ${uploadProgress}%`"
                                 :class="{'success-bounce': uploadProgress === 100}"></div>
                        </div>
                        <div class="flex justify-between text-base text-gray-600">
                            <span class="font-medium" x-text="uploadStatus"></span>
                            <span class="font-mono" x-text="`${Math.round(uploadProgress)}%`"></span>
                        </div>
                    </div>
                    
                    <div class="flex space-x-4 mt-6">
                        <button @click="uploadExcel()" 
                                :disabled="!selectedFile || isUploading"
                                class="flex-1 bg-blue-600 hover:bg-blue-700 disabled:bg-gray-400 disabled:cursor-not-allowed text-white font-bold py-3 px-6 rounded-lg transition-all duration-200 transform hover:scale-105 disabled:hover:scale-100 text-lg">
                            <i class="fas mr-3" :class="isUploading ? 'fa-spinner fa-spin' : 'fa-upload'"></i>
                            <span x-text="getUploadButtonText()"></span>
                        </button>
                        
                        <button x-show="selectedFile && !isUploading" 
                                @click="clearSelectedFile()"
                                class="bg-gray-500 hover:bg-gray-600 text-white font-medium py-3 px-6 rounded-lg transition-colors duration-200">
                            <i class="fas fa-times mr-2"></i>
                            清除选择
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 函数管理区域 -->
        <div class="mb-8">
            <div class="bg-white rounded-xl shadow-lg p-6 border border-gray-200">
                <div class="flex items-center justify-between mb-6">
                    <div class="flex items-center">
                        <div class="bg-green-600 rounded-full p-3 mr-4">
                            <i class="fas fa-code text-white text-xl"></i>
                        </div>
                        <div>
                            <h2 class="text-2xl font-bold text-gray-900">函数管理</h2>
                            <p class="text-gray-600">查看、管理和删除已生成的函数</p>
                        </div>
                    </div>
                    <div class="flex space-x-3">
                        <button @click="loadFunctions()" 
                                class="bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded-lg transition-colors duration-200">
                            <i class="fas fa-refresh mr-2"></i>刷新列表
                        </button>
                        <button @click="clearFunctions()" 
                                :disabled="functions.length === 0"
                                class="bg-red-600 hover:bg-red-700 disabled:bg-gray-400 disabled:cursor-not-allowed text-white px-4 py-2 rounded-lg transition-colors duration-200">
                            <i class="fas fa-trash mr-2"></i>清空所有
                        </button>
                    </div>
                </div>
                
                <!-- 函数列表 -->
                <div class="max-h-96 overflow-y-auto">
                    <template x-for="func in functions" :key="func.name">
                        <div class="bg-gray-50 rounded-lg p-4 mb-3 hover:bg-gray-100 transition-colors duration-200">
                            <div class="flex justify-between items-start">
                                <div class="flex-1">
                                    <div class="flex items-center mb-2">
                                        <h3 class="text-lg font-semibold text-gray-900" x-text="func.name"></h3>
                                        <span class="ml-3 bg-blue-100 text-blue-800 text-xs font-medium px-2 py-1 rounded-full">函数</span>
                                    </div>
                                    <p class="text-gray-700 mb-2" x-text="func.description"></p>
                                    <div class="text-sm text-gray-500 space-y-1">
                                        <div x-show="func.excel_file">
                                            <i class="fas fa-file-excel mr-1"></i>
                                            来源: <span x-text="func.excel_file"></span>
                                        </div>
                                        <div x-show="func.updated_at">
                                            <i class="fas fa-clock mr-1"></i>
                                            更新时间: <span x-text="new Date(func.updated_at).toLocaleString()"></span>
                                        </div>
                                    </div>
                                </div>
                                <button @click="removeFunction(func.name)" 
                                        class="ml-4 bg-red-100 hover:bg-red-200 text-red-600 hover:text-red-700 p-2 rounded-lg transition-colors duration-200"
                                        :title="'删除函数: ' + func.name">
                                    <i class="fas fa-trash-alt"></i>
                                </button>
                            </div>
                        </div>
                    </template>
                    <div x-show="functions.length === 0" class="text-center py-12">
                        <div class="mb-4">
                            <i class="fas fa-inbox text-6xl text-gray-300"></i>
                        </div>
                        <div class="text-xl text-gray-500 mb-2">暂无函数数据</div>
                        <div class="text-gray-400">请上传Excel文件生成函数</div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 智能搜索与系统监控 -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-8 mb-8">

            <!-- 智能函数搜索 -->
            <div class="bg-white rounded-lg shadow-lg p-6">
                <div class="flex items-center mb-6">
                    <i class="fas fa-search text-purple-600 text-2xl mr-3"></i>
                    <h3 class="text-xl font-bold text-gray-900">智能函数搜索</h3>
                </div>

                <!-- RAG 查询 -->
                <div class="mb-6">
                    <div class="flex space-x-2 mb-4">
                        <input type="text" 
                               x-model="queryText" 
                               placeholder="输入查询内容，如：满意度指标"
                               class="flex-1 px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500 text-base">
                        <button @click="runQuery()" 
                                :disabled="!queryText.trim() || isQuerying"
                                class="bg-purple-600 hover:bg-purple-700 disabled:bg-gray-400 disabled:cursor-not-allowed text-white px-6 py-3 rounded-lg transition-colors duration-200"
                                :title="isQuerying ? '搜索中...' : '搜索函数'">
                            <i class="fas" :class="isQuerying ? 'fa-spinner fa-spin' : 'fa-search'"></i>
                        </button>
                    </div>
                    
                    <!-- 查询结果 -->
                    <div x-show="queryResults.length > 0" class="mt-4">
                        <h5 class="font-semibold mb-3 text-gray-700">
                            找到 <span class="text-purple-600" x-text="queryResults.length"></span> 个相关函数:
                        </h5>
                        <div class="max-h-64 overflow-y-auto space-y-2">
                            <template x-for="result in queryResults" :key="result.function_name">
                                <div class="bg-purple-50 border border-purple-200 rounded-lg p-3 hover:bg-purple-100 transition-colors">
                                    <div class="flex justify-between items-start">
                                        <div class="flex-1">
                                            <div class="font-medium text-purple-900" x-text="result.function_name"></div>
                                            <div class="text-sm text-purple-700 mt-1" x-text="result.description"></div>
                                        </div>
                                        <div class="ml-3">
                                            <div class="text-xs text-purple-600 bg-purple-200 px-2 py-1 rounded-full font-medium">
                                                <span x-text="(result.similarity_score * 100).toFixed(1)"></span>%
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </template>
                        </div>
                    </div>
                    
                    <!-- 无结果提示 -->
                    <div x-show="queryResults.length === 0 && queryText && !isQuerying" class="mt-4 p-4 bg-yellow-50 border border-yellow-200 rounded-lg">
                        <div class="flex items-center">
                            <i class="fas fa-search text-yellow-600 mr-2"></i>
                            <span class="text-yellow-800">未找到相关函数，请尝试其他关键词</span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 系统管理 -->
            <div class="bg-white rounded-lg shadow-lg p-6">
                <div class="flex items-center mb-6">
                    <i class="fas fa-cogs text-orange-600 text-2xl mr-3"></i>
                    <h3 class="text-xl font-bold text-gray-900">系统管理</h3>
                </div>

                <!-- 管理操作 -->
                <div class="space-y-3 mb-6">
                    <button @click="rollbackServer()" 
                            :disabled="!serviceStatus.server.online"
                            class="w-full bg-yellow-600 hover:bg-yellow-700 disabled:bg-gray-400 disabled:cursor-not-allowed text-white font-medium py-2 px-4 rounded-lg transition-colors duration-200"
                            :title="serviceStatus.server.online ? '回退到备份版本' : '服务器离线，无法操作'">
                        <i class="fas fa-undo mr-2"></i>
                        回退到备份版本
                    </button>
                </div>

                <!-- 快速链接 -->
                <div class="space-y-2">
                    <h5 class="font-semibold text-gray-700 mb-3">API文档</h5>
                    <a :href="'http://localhost:8010/docs'" target="_blank" 
                       class="block w-full bg-blue-50 hover:bg-blue-100 text-blue-700 font-medium py-2 px-3 rounded-lg transition-colors duration-200 text-center text-sm">
                        <i class="fas fa-external-link-alt mr-2"></i>
                        MCP Generator
                    </a>
                    
                    <a :href="'http://localhost:8011/docs'" target="_blank" 
                       class="block w-full bg-purple-50 hover:bg-purple-100 text-purple-700 font-medium py-2 px-3 rounded-lg transition-colors duration-200 text-center text-sm">
                        <i class="fas fa-external-link-alt mr-2"></i>
                        MCP Server
                    </a>
                    
                    <a :href="'http://localhost:8080/docs'" target="_blank" 
                       class="block w-full bg-green-50 hover:bg-green-100 text-green-700 font-medium py-2 px-3 rounded-lg transition-colors duration-200 text-center text-sm">
                        <i class="fas fa-external-link-alt mr-2"></i>
                        Agent Client
                    </a>
                </div>
            </div>
        </div>

        <!-- 系统状态监控 -->
        <div class="bg-white rounded-xl shadow-lg p-6 border border-gray-200">
            <div class="flex items-center justify-between mb-6">
                <div class="flex items-center">
                    <div class="bg-indigo-600 rounded-full p-3 mr-4">
                        <i class="fas fa-chart-line text-white text-xl"></i>
                    </div>
                    <div>
                        <h2 class="text-2xl font-bold text-gray-900">系统状态监控</h2>
                        <p class="text-gray-600">实时监控各服务状态和任务统计</p>
                    </div>
                </div>
                <button @click="refreshAllStatus()" 
                        class="bg-indigo-600 hover:bg-indigo-700 text-white px-4 py-2 rounded-lg transition-colors duration-200">
                    <i class="fas fa-sync-alt mr-2" :class="{'fa-spin': isRefreshing}"></i>
                    刷新状态
                </button>
            </div>
            
            <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-6">
                <!-- MCP Generator 状态 -->
                <div class="bg-gradient-to-br from-blue-50 to-blue-100 rounded-lg p-4 border border-blue-200">
                    <div class="flex items-center justify-between mb-3">
                        <div>
                            <h3 class="text-lg font-semibold text-blue-900">MCP Generator</h3>
                            <p class="text-sm text-blue-700">端口: 8010</p>
                        </div>
                        <div class="text-right">
                            <span class="status-indicator" :class="getStatusClass('generator')"></span>
                            <span class="text-sm font-medium text-blue-800" x-text="serviceStatus.generator.status"></span>
                        </div>
                    </div>
                    <div class="text-xs text-blue-600">Excel解析 • 函数生成</div>
                </div>

                <!-- MCP Server 状态 -->
                <div class="bg-gradient-to-br from-purple-50 to-purple-100 rounded-lg p-4 border border-purple-200">
                    <div class="flex items-center justify-between mb-3">
                        <div>
                            <h3 class="text-lg font-semibold text-purple-900">MCP Server</h3>
                            <p class="text-sm text-purple-700">端口: 8011</p>
                        </div>
                        <div class="text-right">
                            <span class="status-indicator" :class="getStatusClass('server')"></span>
                            <span class="text-sm font-medium text-purple-800" x-text="serviceStatus.server.status"></span>
                        </div>
                    </div>
                    <div class="text-xs text-purple-600">统一MCP工具 • 服务管理</div>
                </div>

                <!-- Agent Client 状态 -->
                <div class="bg-gradient-to-br from-green-50 to-green-100 rounded-lg p-4 border border-green-200">
                    <div class="flex items-center justify-between mb-3">
                        <div>
                            <h3 class="text-lg font-semibold text-green-900">Agent Client</h3>
                            <p class="text-sm text-green-700">端口: 8080</p>
                        </div>
                        <div class="text-right">
                            <span class="status-indicator" :class="getStatusClass('client')"></span>
                            <span class="text-sm font-medium text-green-800" x-text="serviceStatus.client.status"></span>
                        </div>
                    </div>
                    <div class="text-xs text-green-600">RAG智能搜索 • 报告处理</div>
                </div>
            </div>
            
            <!-- 任务统计 -->
            <div class="bg-gray-50 rounded-lg p-4">
                <h4 class="text-lg font-semibold text-gray-900 mb-3">任务统计</h4>
                <div class="grid grid-cols-5 gap-4">
                    <div class="text-center">
                        <div class="text-2xl font-bold text-blue-600" x-text="taskStats.total || 0"></div>
                        <div class="text-sm text-gray-600">总任务</div>
                    </div>
                    <div class="text-center">
                        <div class="text-2xl font-bold text-yellow-600" x-text="taskStats.running || 0"></div>
                        <div class="text-sm text-gray-600">运行中</div>
                    </div>
                    <div class="text-center">
                        <div class="text-2xl font-bold text-green-600" x-text="taskStats.completed || 0"></div>
                        <div class="text-sm text-gray-600">已完成</div>
                    </div>
                    <div class="text-center">
                        <div class="text-2xl font-bold text-red-600" x-text="taskStats.failed || 0"></div>
                        <div class="text-sm text-gray-600">失败</div>
                    </div>
                    <div class="text-center">
                        <div class="text-2xl font-bold text-gray-600" x-text="functions.length || 0"></div>
                        <div class="text-sm text-gray-600">函数数量</div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 通知消息 -->
    <div x-show="notification.show" 
         x-transition:enter="transition ease-out duration-300"
         x-transition:enter-start="opacity-0 transform translate-y-2"
         x-transition:enter-end="opacity-100 transform translate-y-0"
         x-transition:leave="transition ease-in duration-200"
         x-transition:leave-start="opacity-100 transform translate-y-0"
         x-transition:leave-end="opacity-0 transform translate-y-2"
         class="fixed bottom-4 right-4 z-50">
        <div class="bg-white rounded-lg shadow-lg border-l-4 p-4 max-w-sm"
             :class="{
                'border-green-500': notification.type === 'success',
                'border-red-500': notification.type === 'error',
                'border-yellow-500': notification.type === 'warning',
                'border-blue-500': notification.type === 'info'
             }">
            <div class="flex">
                <div class="flex-shrink-0">
                    <i class="text-lg"
                       :class="{
                           'fas fa-check-circle text-green-500': notification.type === 'success',
                           'fas fa-exclamation-circle text-red-500': notification.type === 'error',
                           'fas fa-exclamation-triangle text-yellow-500': notification.type === 'warning',
                           'fas fa-info-circle text-blue-500': notification.type === 'info'
                       }"></i>
                </div>
                <div class="ml-3">
                    <p class="text-sm font-medium text-gray-900" x-text="notification.title"></p>
                    <p class="text-sm text-gray-600" x-text="notification.message"></p>
                </div>
                <div class="ml-auto pl-3">
                    <button @click="notification.show = false" class="text-gray-400 hover:text-gray-600">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script>
        function mcpDashboard() {
            return {
                // 服务状态
                serviceStatus: {
                    generator: { online: false, status: '检查中...' },
                    server: { online: false, status: '检查中...' },
                    client: { online: false, status: '检查中...' }
                },
                
                // 状态标识
                isRefreshing: false,
                isUploading: false,
                isQuerying: false,
                isDragOver: false,
                dragError: false,
                
                // 上传相关
                uploadProgress: 0,
                uploadStatus: '',
                dragErrorMessage: '',
                
                // 数据
                functions: [],
                queryText: '',
                queryResults: [],
                taskStats: {},
                selectedFile: null,
                
                // 通知
                notification: {
                    show: false,
                    type: 'info',
                    title: '',
                    message: ''
                },

                // 初始化
                init() {
                    this.refreshAllStatus();
                    this.loadFunctions();
                    this.loadTasks();
                    
                    // 定时刷新状态（每30秒）
                    setInterval(() => {
                        this.refreshAllStatus();
                        this.loadTasks();
                    }, 30000);
                },

                // 显示通知
                showNotification(type, title, message, duration = 5000) {
                    this.notification = { show: true, type, title, message };
                    setTimeout(() => {
                        this.notification.show = false;
                    }, duration);
                },

                // 获取状态样式类
                getStatusClass(service) {
                    const status = this.serviceStatus[service];
                    if (status.status === '检查中...') return 'status-loading';
                    return status.online ? 'status-online' : 'status-offline';
                },

                // 刷新所有服务状态
                async refreshAllStatus() {
                    this.isRefreshing = true;
                    
                    const services = [
                        { key: 'generator', url: 'http://localhost:8010/health', name: 'MCP Generator' },
                        { key: 'server', url: 'http://localhost:8011/health', name: 'MCP Server' },
                        { key: 'client', url: 'http://localhost:8080/health', name: 'Agent Client' }
                    ];

                    for (const service of services) {
                        try {
                            const response = await fetch(service.url);
                            if (response.ok) {
                                this.serviceStatus[service.key] = { online: true, status: '在线' };
                            } else {
                                this.serviceStatus[service.key] = { online: false, status: '离线' };
                            }
                        } catch (error) {
                            this.serviceStatus[service.key] = { online: false, status: '离线' };
                        }
                    }
                    
                    this.isRefreshing = false;
                },

                // 处理文件选择
                handleFileSelect(event) {
                    const file = event.target.files[0];
                    if (file) {
                        // 如果之前有文件且已上传完成，先清除状态
                        if (this.selectedFile && this.uploadStatus.includes('完成')) {
                            this.uploadProgress = 0;
                            this.uploadStatus = '';
                        }
                        this.validateAndSetFile(file);
                    }
                },

                // 验证并设置文件
                validateAndSetFile(file) {
                    // 重置错误状态
                    this.dragError = false;
                    this.dragErrorMessage = '';
                    
                    // 验证文件类型
                    const allowedTypes = ['.xlsx', '.xls'];
                    const fileExtension = file.name.toLowerCase().substring(file.name.lastIndexOf('.'));
                    
                    if (!allowedTypes.includes(fileExtension)) {
                        this.dragError = true;
                        this.dragErrorMessage = '仅支持 .xlsx 或 .xls 格式';
                        this.showNotification('error', '文件类型错误', '请选择 .xlsx 或 .xls 格式的Excel文件');
                        return false;
                    }
                    
                    // 验证文件大小（10MB限制）
                    if (file.size > 10 * 1024 * 1024) {
                        this.dragError = true;
                        this.dragErrorMessage = '文件大小超过10MB限制';
                        this.showNotification('error', '文件太大', '文件大小不能超过10MB');
                        return false;
                    }
                    
                    this.selectedFile = file;
                    this.showNotification('success', '文件选择成功', `已选择文件: ${file.name}`);
                    return true;
                },

                // 拖拽处理
                handleDragOver(event) {
                    event.preventDefault();
                    this.isDragOver = true;
                    this.dragError = false;
                },

                handleDragLeave(event) {
                    event.preventDefault();
                    this.isDragOver = false;
                },

                handleDrop(event) {
                    event.preventDefault();
                    this.isDragOver = false;
                    
                    const files = event.dataTransfer.files;
                    if (files.length > 0) {
                        const file = files[0];
                        // 如果之前有文件且已上传完成，先清除状态
                        if (this.selectedFile && this.uploadStatus.includes('完成')) {
                            this.uploadProgress = 0;
                            this.uploadStatus = '';
                        }
                        if (this.validateAndSetFile(file)) {
                            // 文件验证成功，清除input的值以防冲突
                            document.getElementById('excelFile').value = '';
                        }
                    }
                },

                // 清除选择的文件
                clearSelectedFile() {
                    this.selectedFile = null;
                    this.dragError = false;
                    this.dragErrorMessage = '';
                    this.uploadProgress = 0;
                    this.uploadStatus = '';
                    document.getElementById('excelFile').value = '';
                    this.showNotification('info', '已清除', '文件选择已清除');
                },

                // 格式化文件大小
                formatFileSize(bytes) {
                    if (!bytes) return '0 B';
                    const k = 1024;
                    const sizes = ['B', 'KB', 'MB', 'GB'];
                    const i = Math.floor(Math.log(bytes) / Math.log(k));
                    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
                },

                // 获取上传按钮文本
                getUploadButtonText() {
                    if (this.isUploading) {
                        return this.uploadStatus || '上传中，请稍候...';
                    }
                    return this.selectedFile ? '上传并生成函数' : '请先选择文件';
                },

                // 上传Excel文件
                async uploadExcel() {
                    if (!this.selectedFile) {
                        this.showNotification('warning', '警告', '请先选择Excel文件');
                        return;
                    }

                    this.isUploading = true;
                    this.uploadProgress = 0;
                    this.uploadStatus = '准备上传...';
                    
                    const formData = new FormData();
                    formData.append('file', this.selectedFile);

                    try {
                        // 模拟上传进度
                        this.simulateUploadProgress();
                        
                        const response = await fetch('http://localhost:8010/upload-and-generate', {
                            method: 'POST',
                            body: formData
                        });

                        if (response.ok) {
                            this.uploadProgress = 90;
                            this.uploadStatus = '处理文件中...';
                            
                            const result = await response.json();
                            
                            // 检查是否真正成功
                            if (result.success !== false) {
                                this.uploadProgress = 100;
                                this.uploadStatus = '完成！';
                                
                                this.showNotification('success', '上传成功', 
                                    `文件 "${this.selectedFile.name}" 上传成功！${result.message || '正在生成函数代码...'}`);
                                
                                // 延迟加载函数列表，确保服务器端已更新
                                setTimeout(() => {
                                    this.loadFunctions();
                                    this.refreshAllStatus();
                                }, 2000);
                                
                                // 不自动清除文件，让用户手动清除或选择新文件时自动替换
                                // 显示成功状态，让用户知道可以继续操作
                                setTimeout(() => {
                                    this.uploadStatus = '上传完成，可以选择新文件或手动清除';
                                    this.showNotification('info', '提示', '文件处理完成，您可以选择新文件继续上传，或点击"清除选择"按钮');
                                }, 3000);
                            } else {
                                // 虽然HTTP状态是200，但业务逻辑失败
                                this.uploadProgress = 0;
                                this.uploadStatus = '处理失败';
                                this.showNotification('error', '处理失败', 
                                    result.message || '函数生成过程中发生错误，已回滚所有更改');
                            }
                            
                        } else {
                            const error = await response.json();
                            this.uploadProgress = 0;
                            this.uploadStatus = '上传失败';
                            this.showNotification('error', '上传失败', 
                                error.detail || error.message || '服务器处理文件时发生错误');
                        }
                    } catch (error) {
                        this.uploadProgress = 0;
                        this.uploadStatus = '网络错误';
                        this.showNotification('error', '网络错误', 
                            '无法连接到MCP Generator服务，请检查服务是否正常运行');
                        console.error('上传错误:', error);
                    }

                    this.isUploading = false;
                },

                // 模拟上传进度
                simulateUploadProgress() {
                    const interval = setInterval(() => {
                        if (this.uploadProgress < 70) {
                            this.uploadProgress += Math.random() * 15;
                            if (this.uploadProgress < 30) {
                                this.uploadStatus = '上传文件中...';
                            } else if (this.uploadProgress < 60) {
                                this.uploadStatus = '解析Excel文件...';
                            } else {
                                this.uploadStatus = '生成函数代码...';
                            }
                        } else {
                            clearInterval(interval);
                        }
                    }, 200);
                },

                // 加载函数列表
                async loadFunctions() {
                    try {
                        const response = await fetch('http://localhost:8010/functions');
                        if (response.ok) {
                            const data = await response.json();
                            const oldCount = this.functions.length;
                            this.functions = data.functions || [];
                            const newCount = this.functions.length;
                            
                            console.log(`加载了 ${newCount} 个函数`);
                            
                            // 如果函数数量有变化，显示通知
                            if (newCount > oldCount) {
                                this.showNotification('success', '函数更新', 
                                    `发现 ${newCount - oldCount} 个新函数，当前共有 ${newCount} 个函数`);
                            } else if (newCount < oldCount) {
                                this.showNotification('info', '函数更新', 
                                    `函数列表已更新，当前共有 ${newCount} 个函数`);
                            }
                        } else {
                            console.error('加载函数列表失败，状态码:', response.status);
                            this.showNotification('warning', '警告', '无法加载函数列表，请检查MCP Generator服务状态');
                        }
                    } catch (error) {
                        console.error('加载函数列表失败:', error);
                        this.showNotification('error', '网络错误', '无法连接到MCP Generator服务');
                    }
                },

                // 执行查询
                async runQuery() {
                    if (!this.queryText.trim()) {
                        this.showNotification('warning', '警告', '请输入查询内容');
                        return;
                    }

                    this.isQuerying = true;
                    this.queryResults = [];

                    try {
                        const response = await fetch(`http://localhost:8080/api/rag/search?query=${encodeURIComponent(this.queryText)}&top_k=15`);
                        if (response.ok) {
                            const data = await response.json();
                            this.queryResults = data.results || [];
                            if (this.queryResults.length > 0) {
                                this.showNotification('success', '查询成功', `找到 ${this.queryResults.length} 个相关函数`);
                            }
                        } else {
                            const error = await response.json();
                            this.showNotification('error', '查询失败', error.detail || '无法执行RAG搜索');
                        }
                    } catch (error) {
                        console.error('RAG查询错误:', error);
                        this.showNotification('error', '网络错误', '无法连接到Agent Client服务');
                    }

                    this.isQuerying = false;
                },

                // 加载任务统计
                async loadTasks() {
                    try {
                        const response = await fetch('http://localhost:8080/api/tasks/stats');
                        if (response.ok) {
                            this.taskStats = await response.json();
                        }
                    } catch (error) {
                        console.error('加载任务统计失败:', error);
                        // 设置默认值
                        this.taskStats = { total: 0, running: 0, completed: 0, pending: 0, failed: 0 };
                    }
                },

                // 回退服务器
                async rollbackServer() {
                    if (!confirm('确定要回退到备份版本吗？此操作不可逆。')) {
                        return;
                    }

                    try {
                        const response = await fetch('http://localhost:8011/rollback', {
                            method: 'POST'
                        });

                        if (response.ok) {
                            const result = await response.json();
                            this.showNotification('success', '回退成功', result.message || '服务器已回退到备份版本');
                            // 刷新服务状态
                            setTimeout(() => {
                                this.refreshAllStatus();
                            }, 2000);
                        } else {
                            const error = await response.json();
                            this.showNotification('error', '回退失败', error.message || error.detail || '未知错误');
                        }
                    } catch (error) {
                        this.showNotification('error', '网络错误', '无法连接到MCP Server服务');
                    }
                },

                // 删除单个函数
                async removeFunction(functionName) {
                    if (!confirm(`确定要删除函数 "${functionName}" 吗？此操作不可逆。`)) {
                        return;
                    }

                    // 显示删除进度
                    this.showNotification('info', '删除中', `正在删除函数 "${functionName}"...`);

                    try {
                        const response = await fetch('http://localhost:8011/functions', {
                            method: 'DELETE',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify({
                                function_name: functionName
                            })
                        });

                        if (response.ok) {
                            const result = await response.json();
                            this.showNotification('success', '删除成功', 
                                result.message || `函数 "${functionName}" 已被成功删除`);
                            
                            // 立即从本地列表中移除，提供即时反馈
                            this.functions = this.functions.filter(func => func.name !== functionName);
                            
                            // 延迟刷新以确保服务器状态同步（增加延迟时间）
                            setTimeout(() => {
                                this.loadFunctions();
                                this.refreshAllStatus();
                            }, 3000);  // 增加到3秒，确保MCP Server重启完成
                        } else {
                            const error = await response.json();
                            this.showNotification('error', '删除失败', 
                                error.message || error.detail || `删除函数 "${functionName}" 时发生错误`);
                        }
                    } catch (error) {
                        this.showNotification('error', '网络错误', 
                            '无法连接到MCP Server服务，请检查服务是否正常运行');
                        console.error('删除函数错误:', error);
                    }
                },

                // 清空函数
                async clearFunctions() {
                    const functionCount = this.functions.length;
                    if (!confirm(`确定要清空所有 ${functionCount} 个函数吗？此操作不可逆，将删除所有生成的函数代码。`)) {
                        return;
                    }

                    // 显示清空进度
                    this.showNotification('info', '清空中', `正在清空所有 ${functionCount} 个函数...`);

                    try {
                        const response = await fetch('http://localhost:8011/clear-functions', {
                            method: 'DELETE'
                        });

                        if (response.ok) {
                            const result = await response.json();
                            this.showNotification('success', '清空成功', 
                                result.message || `成功清空了所有 ${functionCount} 个函数`);
                            
                            // 立即清空本地列表，提供即时反馈
                            this.functions = [];
                            
                            // 延迟刷新以确保服务器状态同步（增加延迟时间）
                            setTimeout(() => {
                                this.loadFunctions();
                                this.refreshAllStatus();
                            }, 3000);  // 增加到3秒，确保MCP Server重启完成
                        } else {
                            const error = await response.json();
                            this.showNotification('error', '清空失败', 
                                error.message || error.detail || '清空函数时发生错误');
                        }
                    } catch (error) {
                        this.showNotification('error', '网络错误', 
                            '无法连接到MCP Server服务，请检查服务是否正常运行');
                        console.error('清空函数错误:', error);
                    }
                }
            }
        }
    </script>
</body>
</html>
